﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using System.Data.Entity; // needed for lambda includes

using System.Xml;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Threading.Tasks;

using Newtonsoft.Json;
using System.IO.Compression;

namespace TheCup.ApiControllers
{
    public class GolfnewsController : ApiController
    {
        // GET api/<controller>
        [Route("api/golfnews/golfdk")]
        public IEnumerable<NewsItem> GetGolfDKNews()
        {
            Uri url = new Uri("http://www.golf.dk/news/feed");
            var client = new WebClient();
            client.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");
            //client.Headers.Add("Accept-Encoding", "gzip");
            client.Encoding = Encoding.UTF8;

            byte[] xmlData = client.DownloadData(url);
            //byte[] xmlData = null;
            //using (GZipStream stream = new GZipStream(new MemoryStream(gzippedData), CompressionMode.Decompress))
            //{
            //    stream.Read(xmlData, 0, gzippedData.Length);
            //}
            
            string xmlString = Encoding.UTF8.GetString(xmlData);

            XNamespace dc = "http://purl.org/dc/elements/1.1/";
            XDocument xml = XDocument.Parse(xmlString);
            
            IEnumerable<NewsItem> news =
                (from story in xml.Descendants("item")
                 select new NewsItem
                 {
                     Title = (string)story.Element("title"),
                     Link = (string)story.Element("link"),
                     Description = (string)story.Element("description"),
                     PublishedDate = DateTime.Parse(((string)story.Element("pubDate"))).ToString("s"),
                     Guid = (string)story.Element("guid"),
                     Creator = (string)story.Element(dc + "creator")
                 }).ToList();

            return news;
        }

    }
}